﻿<template>
  <base-dialog
    destroy-on-close
    :width="1200"
    :title="
      modalType === 'view' && relatedType === 1
        ? '已关联类目'
        : modalType === 'view' && relatedType === 2
          ? '已关联商品'
          : '关联商品'
    "
    @close="handleHide"
    v-model="modalShow"
  >
    <div v-if="modalType === 'add'">
      选择类型：<el-radio-group v-model="relatedType" @change="changeRelatedType">
        <el-radio :value="2" size="large">关联商品</el-radio>
        <el-radio :value="1" size="large">关联类目</el-radio>
      </el-radio-group>
    </div>
    <!-- 搜索栏 -->
    <avue-table-search
      v-if="relatedType === 2"
      :option="relatedSearch"
      v-model="relatedSearchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    >
    </avue-table-search>
    <div v-if="relatedType === 1">
      选择类目： <el-cascader v-model="currentCategory" :options="categoryData" :style="{ width: '350px' }" />
    </div>
    <el-checkbox v-model="checkAll" @change="allSelect" v-if="relatedType === 2">全选搜索结果</el-checkbox>
    <avue-crud
      v-if="relatedType === 2"
      ref="goodsListRef"
      :option="tableOption"
      :data="tableData"
      :page="page"
      :table-loading="tableLoading"
      @selection-change="handleSelectionChange"
      @refresh-change="loadTableSearch"
      @current-change="loadTablePageChange"
      @size-change="loadTablePageSizeChange"
    >
      <template #productType="{ row }">
        {{ row.productType === 1 ? "全新" : row.productType === 2 ? "二手" : "-" }}
      </template>

      <template #cate="{ row }">
        {{ goodsCategory(row) }}
      </template>

      <template #rentObject="{ row }">
        {{ leaseType(row.rentObject) }}
      </template>

      <template #rentPlan="{ row }">
        {{ row.rentPlan === 1 ? "统一方案" : row.rentPlan === 2 ? "指定方案" : "-" }}
      </template>

      <template #channelType="{ row }">
        {{
          row.channelType === 1
            ? "全部渠道"
            : row.productType === 2
              ? "部分渠道"
              : row.productType === 3
                ? "芝麻租赁"
                : "-"
        }}
      </template>
    </avue-crud>

    <template #footer>
      <el-button @click="handleHide">取消</el-button>
      <el-button type="primary" @click="handleSaveRelatedProductData">确认选择</el-button>
    </template>
  </base-dialog>
</template>
<script setup>
  import Option from "@/crudOption/product-category/related.js";
  const { relatedSearch, tableOption } = Option();

  const props = defineProps({
    // 显示隐藏
    visble: { type: Boolean, default: false },
    // 当前分类数据
    currentInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // 类目数据
    categoryData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 弹窗类型
    modalType: { type: String, default: "" },
  });
  const emit = defineEmits(["hide", "confirm"]);
  // 监听显隐
  watch(
    () => props.visble,
    v => {
      modalShow.value = v;
      if (props.visble) {
        init();
      }
    }
  );
  // 显示、隐藏
  const modalShow = ref(props.show);
  // 列表ref
  const goodsListRef = ref();
  // 关联选择
  const relatedType = ref();
  // 当前选择类目
  const currentCategory = ref([]);
  // 全选
  const checkAll = ref(false);
  // 当前选中数据
  const currentSelectData = ref([]);
  // 租赁对象
  const leaseType = computed(() => {
    return el => {
      if (el && el.indexOf(",") !== -1) {
        return "全部";
      }
      if (el && ["1", "2"].includes(el)) {
        return el === "1" ? "个人" : el === "2" ? "企业" : "-";
      }
      return "-";
    };
  });
  // 商品类目
  const goodsCategory = computed(() => {
    return info => {
      const categoryGroup = [];
      props.categoryData?.forEach(firstLeveItem => {
        if (info.firstCategoryId && firstLeveItem.value === info.firstCategoryId) {
          categoryGroup.push(firstLeveItem.label);
          // 查询一级类目名称
          firstLeveItem?.children?.forEach(secondLevelItem => {
            if (info.secondCategoryId && secondLevelItem.value === info.secondCategoryId) {
              // 查询二级类目名称
              categoryGroup.push(secondLevelItem.label);
              secondLevelItem?.children?.forEach(thirdLevelItem => {
                if (info.brandId && thirdLevelItem.value === info.brandId) {
                  // 查询三级类目名称
                  categoryGroup.push(thirdLevelItem.label);
                  thirdLevelItem?.children?.forEach(fourthLevelItem => {
                    // 查询四级类目名称
                    if (info.modelId && fourthLevelItem.value === info.modelId) {
                      categoryGroup.push(fourthLevelItem.label);
                    }
                  });
                }
              });
            }
          });
        }
      });
      return categoryGroup.length ? categoryGroup.join("/") : "-";
    };
  });
  // 初始化
  const init = () => {
    console.warn(props.currentInfo);
    if (props.currentInfo.manageCommodityTypes === 0 || props.currentInfo.manageCommodityTypes === 2) {
      relatedType.value = 2;
      loadGetTableData().then(() => {
        if (props.modalType === "view") {
          nextTick(() => {
            goodsListRef.value.toggleAllSelection();
          });
        }
      });
    } else {
      relatedType.value = 1;
      // if (props.modalType === "view") {
      loadSelectedData();
      // }
    }
  };
  // 切换关联类别
  const changeRelatedType = () => {
    currentSelectData.value = [];
    checkAll.value = false;
    // currentCategory.value = [];
    if (relatedType.value === 2) {
      loadGetTableData();
    }
  };
  // 获取已选择的数据
  const loadSelectedData = () => {
    Api.product.getRelatedProduct({ id: props.currentInfo.id }).then(res => {
      console.warn(res, "已选择数据");
      // currentSelectData.value = res.data;
      if (res.data) {
        const { categoryLevelOneId, categoryLevelTwoId, categoryLevelThreeId, categoryLevelFourId } = res.data;
        currentCategory.value = [
          categoryLevelOneId || "",
          categoryLevelTwoId || "",
          categoryLevelThreeId || "",
          categoryLevelFourId || "",
        ];
      }
    });
  };
  // 选择商品
  const handleSelectionChange = data => {
    console.warn(data, "data");

    if (data.length) {
      currentSelectData.value = data;
    } else {
      currentSelectData.value = [];
    }
  };
  // 全选搜索结果
  const allSelect = () => {
    if (checkAll.value) {
      goodsListRef.value.toggleAllSelection();
    } else {
      goodsListRef.value.clearSelection();
    }
  };
  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: relatedSearchParams,
    get: loadGetTableData,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: params => {
      return props.modalType === "view" ? Api.product.getRelatedProduct(params) : Api.product.getLaunchProduct(params);
    },
    getParamsFormat: params => {
      const searchParams = {
        ...params,
        id: props.currentInfo.id,
      };
      if (params.category && params.category.length) {
        searchParams["firstCategoryId"] = params.category[0];
        searchParams["secondCategoryId"] = params.category[1];
        searchParams["brandId"] = params.category.length >= 3 ? params.category[2] : "";
        searchParams["modelId"] = params.category.length === 4 ? params.category[3] : "";
        delete searchParams.category;
      }
      return searchParams;
    },
  });
  // 保存关联商品
  const handleSaveRelatedProductData = () => {
    const params = {
      classificationId: props.currentInfo.id,
      relateType: relatedType.value,
      isSelectAll: 0,
    };
    if (relatedType.value === 1 && !currentCategory.value.length) {
      $msg.warning("请选择需要关联的类目");
      return;
    }
    if (relatedType.value === 2 && !currentSelectData.value.length && props.modalType === "add") {
      $msg.warning("请选择需要关联的商品");
      return;
    }
    if (relatedType.value === 2 && checkAll.value) {
      //勾选所有商品
      params.isSelectAll = 1;
    } else if (relatedType.value === 1) {
      params["firstCategoryId"] = currentCategory.value[0];
      params["secondCategoryId"] = currentCategory.value[1];
      params["brandId"] = currentCategory.value.length >= 3 ? currentCategory.value[2] : "";
      params["modelId"] = currentCategory.value.length >= 4 ? currentCategory.value[3] : "";
    } else {
      params["productIds"] = currentSelectData.value.map(el => {
        return el.id;
      });
    }
    Api.product.saveRelatedProduct(params).then(() => {
      $msg.success("操作成功");
      handleHide(true);
    });
  };
  // 关闭
  const handleHide = refresh => {
    currentSelectData.value = [];
    checkAll.value = false;
    currentCategory.value = [];
    emit("hide", refresh);
  };
</script>

<style lang="scss" scoped></style>
